import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {UploadFile} from 'ng-zorro-antd';
import {SystemConfigService} from '@core/services/system-config.service';
import {ActivatedRoute} from '@angular/router';
import {environment} from '@env/environment';
import {HttpClient} from '@angular/common/http';
import {DatePipe} from '@angular/common';

@Component({
  selector: 'app-staffs-add',
  templateUrl: './staffs-add.component.html',
  styleUrls: ['./staffs-add.component.less']
})
export class StaffsAddComponent implements OnInit {
  // 响应式表单赋值对象
  validateForm: FormGroup;

  // 各inout名初始赋值
  staffInitInfo: any = {
    staffNo: '',
    loginId: '',
    name: '',
    sex: '',
    phone: '',
    staffType: '',
    entryDate: '',
    identityCard: '',
    birthday: '',
    address: '',
  };

  staffTypes: any;
  isVisible = false;
  roleDetail: any = {
    roles: []
  };
  roleLists: any;
  roleId: any = '';
  isConfirmLoading = false;
  isConfirmLoading1 = false;

  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon : true,
    hidePreviewIconInNonImage: true
  };
  fileList = [];
  previewImage = '';
  previewVisible = false;

  constructor(private fb: FormBuilder ,
              private systemService: SystemConfigService,
              private activatedRoute: ActivatedRoute,
              private http: HttpClient,
              private datePipe: DatePipe
  ) {}

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  ngOnInit() {
    // 查询员工类型下拉列表数据
    this.getStaffsTypes([{
      tableName: 'tb_dic_staff_type',
      orderBy: 'sort',
      objName: 'staffTypes'
    }]);

    this.validateForm = this.fb.group({
      staffNo: [this.staffInitInfo.staffNo, [ Validators.required ] ],
      fullName: [this.staffInitInfo.name],
      sex: [this.staffInitInfo.sex, Validators.required],
      phone: [this.staffInitInfo.phone],
      entryDate: [this.staffInitInfo.entryDate],
      staffType: [this.staffInitInfo.staffType],
      identityCard: [this.staffInitInfo.identityCard],
      birthday: [this.staffInitInfo.birthday],
      address: [this.staffInitInfo.address],
    });
  }

  getStaffsTypes(data) {
    return this.systemService.getStaffsTypes(data).then((response: any) => {
      console.log(response);
      this.staffTypes = response.data.staffTypes.content;
      console.log(this.staffTypes);
    });
  }

  // 用户管理详情
  // userInfoById(id) {
  //   return new Promise((resolve, reject) => {
  //     this.http.get(`${environment.GATEWAYURL}hmconfig/api/users/set/${id}`).subscribe(res => {
  //       resolve(res);
  //     }, error => {
  //       reject(error);
  //     });
  //   });
  // }

  // 用户名绑定时模态窗中保存提交数据时调用的接口
  userInfoUpdate(data) {
    return new Promise((resolve, reject) => {
      this.http.post(`${environment.CONFIGURL}api/users`, data).subscribe(res => {
        resolve(res);
      }, error => {
        reject(error);
      });
    });
  }

  // 用户名绑定时弹出模态窗
  showModal(): void {
    this.isVisible = true;
    this.roleId = '';
    this.roleDetail = {};
    this.roleDetail.roles = [];
    this.getRole().then((data: any) => {
      this.roleLists = data.data;
    }, data => {
    });
  }

  // 用户名绑定时弹出模态窗中的角色下拉框
  getRole() {
    return new Promise((resolve, reject) => {
      this.http.get(`${environment.GATEWAYURL}hmconfig/api/roles/page?pageNum=1&pageSize=9999`).subscribe(res => {
        resolve(res);
      }, error => {
        reject(error);
      });
    });
  }

  // 模态窗保存确认
  handleOk(): void {
    this.isConfirmLoading = true;
    this.rolListSavaData();
    const params = {
      id: this.roleDetail.id,
      loginId: this.roleDetail.loginId,
      remark: this.roleDetail.remark,
      roles: this.roleDetail.roles
    };
    this.staffInitInfo.loginId = this.roleDetail.loginId;
    this.userInfoUpdate(params).then((data: any) => {
      this.ngOnInit();
      this.isVisible = false;
      this.isConfirmLoading = false;
    }, data => {
    });
  }

  // 关闭模态窗
  handleCancel(): void {
    this.isVisible = false;
  }

  // 格式化提交后台的角色数据
  rolListSavaData() {
    const array = [];
    const data = this.roleDetail.roles;
    if (data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        array.push({
          id: data[i].id,
          menuIds: null,
          remark: null,
          name: data[i].name,
          sort: data[i].sort

        });
        array[array.length - 1].isDefault = data[i].isDefault === true ? 1 : (data[i].isDefault == false ? 0 : data[i].isDefault);
      }
    }
    this.roleDetail.roles = array;
  }

  // 添加默认角色
  addRole(rId) {
    if (rId === '' || rId == null) {
      return;
    }
    this.roleDetail.roles = [ ...this.roleDetail.roles, {
      id: this.roleId,
      isDefault: 0,
      name: '',
      sort: this.roleDetail.roles.length
    }];

    for (let i = 0; i < this.roleLists.length; i++) {
      if (rId === this.roleLists[i].id) {
        this.roleDetail.roles[this.roleDetail.roles.length - 1].name = this.roleLists[i].name;
      }
    }
    console.log(this.roleDetail.roles);
  }

  // 删除默认角色
  rDel(rId) {
    this.roleDetail.roles = this.roleDetail.roles.filter(d => d.id !== rId);
  }

  // 保存提交数据
  saveEdit(staff) {
    console.log(staff);
    console.log(this.fileList);
    staff.entryDate = this.datePipe.transform( staff.entryDate, 'yyyy-MM-dd');
    staff.birthday = this.datePipe.transform( staff.birthday, 'yyyy-MM-dd');
    // this.http.post(`${environment.CONFIGURL}api/staffs`, staff).subscribe(response => {
    //   console.log(response);
    //   // this.goBack();
    // });
  }

  // 取消返回列表页
  goBack() {
    history.back();
  }


}
